import { defineStore } from 'pinia'
import { login, logout, getCurrentUser } from '@/api/auth'

/**
 * 使用 meta.roles 判断当前用户是否有权限
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * 通过递归过滤异步路由表
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

export const useUserStore = defineStore('user', {
  state: () => {
    // 从localStorage恢复状态
    const token = localStorage.getItem('token') || ''
    const userInfoStr = localStorage.getItem('userInfo') || '{}'
    let userInfo = {}
    try {
      userInfo = JSON.parse(userInfoStr)
    } catch (e) {
      console.warn('Failed to parse userInfo from localStorage:', e)
      userInfo = {}
    }

    return {
      token,
      userInfo,
      roles: [],
      permissions: []
    }
  },
  
  getters: {
    isLoggedIn: (state) => !!state.token,
    userName: (state) => state.userInfo.nickname || state.userInfo.username || '',
    userAvatar: (state) => state.userInfo.avatar || '',
    userRoles: (state) => state.roles,
    userPermissions: (state) => state.permissions,
    // 检查是否为管理员
    isAdmin: (state) => {
      const role = state.userInfo.role || state.userInfo.userRole
      return ['ADMIN', 'admin', 'SUPER_ADMIN', 'super_admin'].includes(role)
    },
    // 获取用户角色
    userRole: (state) => state.userInfo.role || state.userInfo.userRole || 'CUSTOMER'
  },
  
  actions: {
    // 用户登录
    async login(loginForm) {
      try {
        const response = await login(loginForm)
        console.log('登录API响应:', response)

        // 处理后端返回的格式 {success: true, token: "...", user: {...}}
        if (response && response.success && response.token) {
          const { token, user } = response
          console.log('登录成功，token:', token?.substring(0, 20) + '...')
          console.log('用户信息:', user)

          // 验证用户角色 - 只允许管理员登录
          const userRole = user?.role || user?.userRole || 'CUSTOMER'
          console.log('用户角色:', userRole)

          if (!this.validateAdminRole(userRole)) {
            console.log('角色验证失败:', userRole)
            throw new Error('此系统仅限管理员使用')
          }

          // 保存token和用户信息
          this.token = token
          this.userInfo = user || {}
          console.log('保存到store - token:', !!this.token)
          console.log('保存到store - userInfo:', this.userInfo)

          // 持久化存储
          localStorage.setItem('token', token)
          localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
          console.log('保存到localStorage完成')

          return { success: true, data: response, user: user }
        } else {
          console.log('登录响应格式错误:', response)
          return { success: false, message: response?.message || '登录失败' }
        }
      } catch (error) {
        console.error('Login error:', error)
        return { success: false, message: error.message || '登录失败' }
      }
    },
    
    // 获取用户信息
    async getUserInfo() {
      try {
        const response = await getCurrentUser()
        if (response && response.data) {
          const userData = response.data
          this.userInfo = userData
          localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
          return { success: true, data: userData }
        } else {
          return { success: false, message: response.message || '获取用户信息失败' }
        }
      } catch (error) {
        console.error('Get user info error:', error)
        return { success: false, message: error.message || '获取用户信息失败' }
      }
    },
    
    // 用户登出
    async logout(callApi = true) {
      if (callApi && this.token) {
        try {
          await logout()
        } catch (error) {
          console.error('Logout API error:', error)
          // API调用失败不影响本地状态清理
        }
      }
      // 清除本地存储
      this.resetState()
    },
    
    // 重置状态
    resetState() {
      this.token = ''
      this.userInfo = {}
      this.roles = []
      this.permissions = []
      
      // 清除本地存储
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    },
    
    // 更新用户信息
    updateUserInfo(userInfo) {
      this.userInfo = { ...this.userInfo, ...userInfo }
      localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
    },
    
    // 设置角色和权限
    setRolesAndPermissions(roles, permissions) {
      this.roles = roles || []
      this.permissions = permissions || []
    },

    // 验证管理员角色
    validateAdminRole(userRole) {
      const allowedRoles = ['ADMIN', 'admin', 'SUPER_ADMIN', 'super_admin']
      return allowedRoles.includes(userRole)
    },

    // 检查当前用户权限
    hasPermission(permission) {
      return this.permissions.includes(permission) || this.isAdmin
    },

    // 检查当前用户角色
    hasRole(role) {
      return this.roles.includes(role) || (role === 'ADMIN' && this.isAdmin)
    },

    // 初始化用户状态（确保从localStorage正确恢复）
    initializeState() {
      const token = localStorage.getItem('token')
      const userInfoStr = localStorage.getItem('userInfo')

      console.log('初始化状态 - localStorage token:', !!token)
      console.log('初始化状态 - localStorage userInfo:', userInfoStr)

      if (token) {
        this.token = token
        console.log('恢复token到store')
      } else {
        console.log('localStorage中没有token')
      }

      if (userInfoStr) {
        try {
          this.userInfo = JSON.parse(userInfoStr)
          console.log('恢复userInfo到store:', this.userInfo)
        } catch (e) {
          console.warn('Failed to parse userInfo from localStorage:', e)
          this.userInfo = {}
        }
      } else {
        console.log('localStorage中没有userInfo')
      }

      console.log('初始化完成 - isLoggedIn:', this.isLoggedIn)
      console.log('初始化完成 - isAdmin:', this.isAdmin)
    }
  }
}) 